import axios from "axios"
import { Toast } from "antd-mobile"
let baseUrl = ""
let $pre=""
//判断环境
if (process.env.NODE_ENV === 'development') {
    baseUrl = "/api"
    $pre="http://localhost:1000"
}
export { $pre}

//请求拦截
axios.interceptors.request.use(config => {
    config.url = baseUrl + config.url;
    console.log(config.url);
    ///
    if (config.url != baseUrl + '/api/login' && config.url != baseUrl + '/api/register') {
        config.headers.authorization = JSON.parse(localStorage.getItem("isLogin")).token;
    }
    return config
})

//响应拦截
axios.interceptors.response.use(res => {
    //打印
    console.group("request url:" + res.config.url)
    console.log(res);
    console.groupEnd()
 //失败
 if (res.data.code != 200) {
    Toast.show({
        content: res.data.msg
    })
}
//掉线
if (res.data.msg == "登录已过期或访问权限受限") {
    sessionStorage.removeItem("isLogin")
    window.open("/", "_self")
}
    return res;
})

export const get = (url, params = {}) => {
    return axios({
        url, params
    })
}

export const post = (url, params, haveFile = false)=>{
    let d = null;
    if (haveFile) {
        d = new FormData()
        for (let key in params) {
            d.append(key, params[key])
        }
    } else {
        d = params
    }
  
    return axios({
        url,
        method: "post",
        data: d
    })
}